package com.example.chatroom.api;

import com.example.chatroom.model.User;
import com.example.chatroom.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest request) {
        // 将传过来的用户名和密码去数据库中查, 看一下密码是否匹配
        User user = userMapper.selectUserByUsername(username);

        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("[login] 登录失败, 用户名或密码错误!");
            return new User();
        }

        // 用户名和密码都正确, 创建会话
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);

        // 返回前把密码干掉
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    public Object reg(String username, String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            // 说明名字重复了, 返回 null 对象
            System.out.println("注册失败, username = " + username);
            user = new User();
        }
        return user;
    }

    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest req) {
        // 获取会话
        HttpSession session = req.getSession(false);
        if (session == null) {
            System.out.println("[getUserInfo] session == null");
            return new User();
        }

        // 获取 user 对象
        User user = (User) session.getAttribute("user");
        if (user == null) {
            System.out.println("[getUserInfo] user == null");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
